package cn.wuhan2019mwg.mobile.activity.wuhan2019mwg.activitys;

import android.content.Context;
import android.os.Build;
import android.provider.SyncStateContract;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import cn.wuhan2019mwg.mobile.activity.wuhan2019mwg.R;
import cn.wuhan2019mwg.mobile.activity.wuhan2019mwg.base.BaseActivity;
import cn.wuhan2019mwg.mobile.activity.wuhan2019mwg.mwgapplication.WuhanMwgApplication;
import cn.wuhan2019mwg.mobile.activity.wuhan2019mwg.utils.Abstract;
import cn.wuhan2019mwg.mobile.activity.wuhan2019mwg.utils.Constance;

/**
 * Created by dell on 2017/10/30.
 */

public class OtherWebActivity extends BaseActivity implements View.OnClickListener{

    private ImageView iv_go_back;
    private AppCompatTextView tv_webtitle;
    private ProgressBar pb_other_progress;
    private WebView wb_other;
    private String url;
    private RelativeLayout rl_go_back;
    protected AsyncHttpClient asyncHttpClient;
    private String tag ="OtherWebActivity";
    private int type =0;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_other_web;
    }

    @Override
    protected void initView() {
        url = getIntent().getStringExtra(Constance.URL);
        type = getIntent().getIntExtra(Constance.TYPE,0);
        iv_go_back = (ImageView) findViewById(R.id.iv_go_back);
        tv_webtitle = (AppCompatTextView) findViewById(R.id.tv_webtitle);
        tv_webtitle.setSelected(true);
        pb_other_progress = (ProgressBar) findViewById(R.id.pb_other_progress);
        rl_go_back = (RelativeLayout) findViewById(R.id.rl_go_back);
        wb_other = (WebView) findViewById(R.id.wb_other);
        rl_go_back.setOnClickListener(this);
    }

    @Override
    protected void initData() {

//        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, WuhanMwgApplication.strcookie+ "; path=/");//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync();


        setWebClient();
        if (asyncHttpClient == null) {
            asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.setTimeout(20000);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case  R.id.rl_go_back:
                if (wb_other.canGoBack()){
                    wb_other.goBack();
                }else {
                    finish();
                }

                break;

        }
    }

    private void setWebClient(){
        wb_other.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wb_other.getSettings().setJavaScriptEnabled(true);// 设置可用JS
        wb_other.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        wb_other.getSettings().setUseWideViewPort(true);
        wb_other.getSettings().setLoadWithOverviewMode(true);
        wb_other.getSettings().setSaveFormData(true);
        wb_other.getSettings().setAllowFileAccess(true);
        wb_other.getSettings().setGeolocationEnabled(true);
        wb_other.getSettings().setDomStorageEnabled(true);




        WindowManager wm = (WindowManager) OtherWebActivity.this.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        if(width > 650)
        {
            this.wb_other.setInitialScale(190);
        }else if(width > 520)
        {
            this.wb_other.setInitialScale(160);
        }else if(width > 450)
        {
            this.wb_other.setInitialScale(140);
        }else if(width > 300)
        {
            this.wb_other.setInitialScale(120);
        }else
        {
            this.wb_other.setInitialScale(100);
        }


        wb_other.setWebViewClient(new WebViewClient(){



            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    view.loadUrl(request.getUrl().toString());


                }
                Log.e("strurl","WebResourceRequest"+url);
                //wb_other.loadUrl("javascript:sayHello()");

                return true;
            }

//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//                Log.e("strurl", "String url " + url);
//                if(type==1)
//                {
//                    Log.e(tag, "shouldOverrideUrlLoading" );
//                    type = 0;
//                    view.loadUrl("http://uc.wuhan2019mwg.cn/index.php?m=member&c=index&a=login");
//                }
//                return true;
//            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
        });

        wb_other.setWebChromeClient(new WebChromeClient(){

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    pb_other_progress.setVisibility(View.GONE);
//                    wb_other.loadUrl("javascript:test()");
//                    wb_other.evaluateJavascript("javascript:test()", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String result) {
//                            Log.e(tag,"result "+result);
//                            if(result.equals("0"))
//                            {
//
//                            }
//                            else if(result.equals("1"))
//                            {
//
//                            }
//                        }
//                    });

                    wb_other.evaluateJavascript("javascript:showjson()", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String user) {

                            if(user!=null && user.length()>30)
                            {
                                WuhanMwgApplication.anAbstract = gson.fromJson(user, Abstract.class);
                                Log.e(tag,"user "+user);
                                finish();
                            }

                        }
                    });

                    if(type==1)
                    {
                        Log.e(tag, "newProgress == 100" );
                        type=0;
                        wb_other.loadUrl("http://uc.wuhan2019mwg.cn/index.php?m=member&c=index");
                        Log.e(tag, "newProgress == 101" );
                    }

//                    wb_other.evaluateJavascript("javascript:del()", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String del) {
//
//                        }
//                    });



                } else {
                    // 加载中
                    pb_other_progress.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                tv_webtitle.setText(title);
                //Log.e("strurl",title);
            }
        });
        wb_other.loadUrl(url);



    }


//    @JavascriptInterface
//    public void onTest(String result) {
//        Log.e(tag,"result1"+result);
//    }

    @Override
    public void onBackPressed() {
        if (wb_other.canGoBack()){
            wb_other.goBack();
        }else {
            finish();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        wb_other.clearCache(true);
        wb_other.clearHistory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }


    private void getInfo() {


        asyncHttpClient.get(this, "http://uc.wuhan2019mwg.cn/index.php?m=member", new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String s) {
                super.onSuccess(s);
                Log.e(tag, s);

//                ConsultationListO consultationListO = gson.fromJson(s, ConsultationListO.class);

            }

            @Override
            public void onFailure(Throwable throwable, String s) {
                super.onFailure(throwable, s);

            }
        });
    }

}
